<template>
  <div class="feedback-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>意见反馈管理</span>
          <el-button type="primary" size="small" @click="fetchFeedbackList">刷新数据</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索反馈内容"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="statusFilter" placeholder="处理状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="未处理" value="未处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
        </el-select>
        
        <el-button type="primary" @click="searchFeedback">搜索</el-button>
      </div>
      
      <!-- 反馈列表表格 -->
      <el-table
        :data="feedbackList"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="consultation_id" label="反馈ID" width="80" />
        <el-table-column prop="user_name" label="用户名" width="120" />
        <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="submitted_at" label="提交时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewFeedbackDetails(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              v-if="scope.row.status !== '已完成'"
              @click="handleFeedback(scope.row)"
            >
              {{ scope.row.status === '未处理' ? '处理' : '完成' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="feedbackDetailVisible"
      title="反馈详情"
      width="600px"
    >
      <div v-if="currentFeedback" class="feedback-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="反馈ID">{{ currentFeedback.consultation_id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentFeedback.user_name }}</el-descriptions-item>
          <el-descriptions-item label="内容">{{ currentFeedback.content }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ currentFeedback.submitted_at }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentFeedback.status)">
              {{ currentFeedback.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentFeedback.reply" class="reply-section">
          <h4>回复内容</h4>
          <p>{{ currentFeedback.reply }}</p>
        </div>
        
        <div v-if="currentFeedback.status !== '已完成'" class="reply-form">
          <h4>回复</h4>
          <el-form>
            <el-form-item>
              <el-input
                v-model="replyContent"
                type="textarea"
                :rows="4"
                placeholder="请输入回复内容"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitReply">提交回复</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const searchQuery = ref('')  // 用于content查询
const statusFilter = ref('') // 用于status查询
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const feedbackList = ref([])
const feedbackDetailVisible = ref(false)
const currentFeedback = ref(null)
const replyContent = ref('')

// 状态映射，跟后端status对应
const getStatusTag = (status) => {
  const statusMap = {
    '未处理': 'danger',
    '处理中': 'warning',
    '已完成': 'success'
  }
  return statusMap[status] || 'info'
}

// 根据后端API调整参数名：content 和 status
const fetchFeedbackList = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/consultation/consultationsList', {
      params: {
        content: searchQuery.value,
        status: statusFilter.value
      }
    })
    console.log('API响应数据:', response.data)
    if (Array.isArray(response.data)) {
      feedbackList.value = response.data.map(item => ({
        consultation_id: item.consultation_id,
        user_name: item.user_name,
        content: item.content,
        submitted_at: item.submitted_at,
        status: item.status,
        reply: item.reply
      }))
      total.value = feedbackList.value.length
    } else {
      ElMessage.error('获取反馈列表失败')
    }
  } catch (error) {
    console.error('获取反馈列表失败:', error)
    ElMessage.error('获取反馈列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const searchFeedback = () => {
  currentPage.value = 1
  fetchFeedbackList()
}

const viewFeedbackDetails = (feedback) => {
  currentFeedback.value = feedback
  replyContent.value = feedback.reply || ''  // 显示已有回复内容
  feedbackDetailVisible.value = true
}

const handleFeedback = (feedback) => {
  // 根据当前状态决定下一个状态
  let nextStatus = ''
  let actionText = ''
  if(feedback.status === '未处理'){
    nextStatus = '处理中'
    actionText = '开始处理'
  } else if(feedback.status === '处理中'){
    nextStatus = '已完成'
    actionText = '完成处理'
  } else {
    ElMessage.info('该反馈已完成完毕')
    return
  }

  ElMessageBox.confirm(
    `确定要${actionText}该反馈吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await axios.post(`http://127.0.0.1:5000/api/consultation/updateStatus/${feedback.consultation_id}`, {
        status: nextStatus
      })
      ElMessage.success('状态更新成功')
      feedback.status = nextStatus  // 同步更新本地数据
      feedbackList.value = [...feedbackList.value]
    } catch (err) {
      console.error('更新状态失败:', err)
      ElMessage.error('状态更新失败')
    }
  }).catch(() => {
    // 用户点击取消，不做任何事
  })
}

const submitReply = async() => {
if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    await axios.post(`http://127.0.0.1:5000/api/consultation/reply/${currentFeedback.value.consultation_id}`, {
      reply: replyContent.value
    })
    ElMessage.success('回复已提交')
    currentFeedback.value.reply = replyContent.value  // 本地同步更新
    replyContent.value = ''
    feedbackDetailVisible.value = false
  } catch (error) {
    console.error('提交回复失败:', error)
    ElMessage.error('提交回复失败，请稍后重试')
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFeedbackList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchFeedbackList()
}

onMounted(() => {
  fetchFeedbackList()
})
</script>

<style scoped>
.feedback-management {
  width: 100%;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.feedback-detail {
  padding: 10px;
}

.reply-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.reply-section h4 {
  margin-bottom: 10px;
  color: #409EFF;
}

.reply-time {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
  text-align: right;
}

.reply-form {
  margin-top: 20px;
}

.reply-form h4 {
  margin-bottom: 10px;
  color: #409EFF;
}
</style>